import {reactive} from "vue";

const defaultPage = {
    page: 1,
    pageSize: 10
}

export function usePaging(options) {
    const {fn,initParams} = options
    const pager = reactive({
        page: defaultPage.page,
        pageSize: defaultPage.pageSize,
        total: 0
    })
    let listParams = initParams
    const changePage = (page) => {
        pager.page = page
        getListFn(listParams)
    }
    const getListFn = (params = {}) => {
        fn({...listParams, page:pager.page, pageSize:pager.pageSize}).then(res => {
            pager.total = res.pager.total
            pager.pageSize = res.pager.pageSize
            pager.page = res.pager.page
            pager.lists = res.data
            return Promise.resolve(res)
        }).catch(err => {
            return Promise.reject(err)
        })
    }
    const handleQuery = () => {
        getListFn()
    }
    const resetQuery = () => {
        listParams = {}
        pager.page = defaultPage.page
        pager.pageSize = defaultPage.pageSize
        getListFn()
    }
    return {
        pager,
        changePage,
        getListFn,
        handleQuery,
        resetQuery
    }
}